package cfca.seal.web.service;

import cfca.sadk.x509.certificate.X509Cert;
import cfca.seal.exception.CodeException;
import cfca.seal.mananger.TrustCertManager;
import java.io.InputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class TrustCertService
{
  private static final Logger sysLog = LoggerFactory.getLogger("web_sys");

  public boolean importTrustCert(InputStream fis) throws CodeException {
    try {
      X509Cert cert = new X509Cert(fis);
      TrustCertManager.instance.importTrustCert(cert.getSubject(), cert);
      return true;
    } catch (CodeException ce) {
      sysLog.error("code:" + ce.getCode(), ce);
      throw new CodeException(ce.getCode(), ce.getMessage(), ce);
    } catch (Exception e) {
      sysLog.error("添加信任证书失败", e);
      if ((null != e.getMessage()) && (e.getMessage().contains("850411"))) {
        throw new CodeException("C0001", "导入的信任证书格式不正确");
      }
      throw new CodeException("C0001", "添加信任证书失败", e);
    } finally {
      try {
        if (fis != null) {
          fis.close();
          fis = null;
        }
      } catch (Exception e) {
        fis = null;
      }
    }
  }

  public boolean deleteTrustCert(String trustCertDn) throws CodeException
  {
    try {
      TrustCertManager.instance.deleteTrustCert(trustCertDn);
      return true;
    } catch (CodeException ce) {
      sysLog.error("code:" + ce.getCode() + ",mes:" + ce.getMessage(), ce);
      throw ce;
    } catch (Exception e) {
      sysLog.error("删除信任证书失败", e);
      throw new CodeException("C0001", "删除信任证书失败", e);
    }
  }
}